from django.template import RequestContext, loader
from django.views.decorators.http import require_GET, require_http_methods, require_POST
from django.views.decorators.gzip import gzip_page
from django.views.generic import TemplateView, ListView, DetailView

from cita.models import Citacao, Autor, Tag

from django.http import HttpResponse
from django.shortcuts import get_object_or_404, get_list_or_404

@gzip_page
def inicio(requisicao):

    template = loader.get_template('index.html')

    contexto = RequestContext(requisicao)

    return HttpResponse(template.render(contexto))


class Pesquisa (ListView):
    
    context_object_name = 'citacoes'
    template_name = "mostra.html"
    
    def get_queryset(self):
        parametos = self.args[0]
        parametos = parametos.split('+')
        objetos = Citacao.objects.all()
        for parametro in parametos:
            objetos = objetos.filter(texto__icontains = parametro)
        
        return objetos[0:20]
    

class PorAutor(DetailView):
    
    context_object_name = 'autor'
    template_name = 'mostra.html'
    
    def get_queryset(self):
        objetos = Autor.objects.all()
        return objetos

    
    def get_context_data(self, **kwargs):
        contexto = super(DetailView, self).get_context_data(**kwargs)
        contexto['citacoes'] = self.object.citacoes.all()
        return contexto
        

@gzip_page
def porAutor(requisicao, id =''):


    autor = get_object_or_404(Autor, pk = id)

    citacoes = autor.citacoes.all()

    contexto = RequestContext(requisicao)
    contexto['citacoes'] = citacoes
    template = loader.get_template('mostra.html')
    return HttpResponse(template.render(contexto))


@gzip_page
def porTag(requisicao, id = ''):


    tag = get_object_or_404(Tag, pk = id)

    citacoes = tag.citacoes.all()

    contexto = RequestContext(requisicao)
    contexto['citacoes'] = citacoes
    template = loader.get_template('mostra.html')
    return HttpResponse(template.render(contexto))
